package com.glx.test.datafluxaispringboot.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

/**
 * DeepseekUtils
 * @author jluuno
 * AI链接发送接收消息工具类
 */
@Component
public class AliUtils {

    @Value("${ali.api.key}")
    private String apiKey;

    @Value("${ali.api.url}")
    private String apiUrl;

    private static final int MAX_RETRIES = 3;
    private static final int RETRY_DELAY_MS = 1000; // 每次重试间隔时间（毫秒）

    private OkHttpClient client;

    public AliUtils() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时
                .writeTimeout(30, TimeUnit.SECONDS)    // 写入超时
                .readTimeout(30, TimeUnit.SECONDS)     // 读取超时
                .retryOnConnectionFailure(true)        // 允许重试
                .build();
    }

    public String sendRequest(String jsonBody) throws IOException {
        System.out.println("发送请求到: " + apiUrl);
        System.out.println("请求内容: " + jsonBody);

        RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .url(apiUrl)
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(body)
                .build();

        int currentTry = 0;
        while (currentTry < MAX_RETRIES) {
            try {
                Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    String errorBody = response.body() != null ? response.body().string() : "无响应内容";
                    throw new IOException("请求失败，状态码: " + response.code() + ", 错误信息: " + errorBody);
                }
                String responseBody = response.body().string();
                return parseResponse(responseBody);
            } catch (SocketTimeoutException e) {
                currentTry++;
                if (currentTry == MAX_RETRIES) {
                    throw new IOException("请求超时，已达到最大重试次数");
                }
                System.out.println("请求超时，重试 " + currentTry + " 次...");
            } catch (IOException e) {
                currentTry++;
                if (currentTry == MAX_RETRIES) {
                    throw e;
                }
                System.out.println("请求失败，重试 " + currentTry + " 次...");
            }

            // 延迟一段时间后再重试
            try {
                TimeUnit.MILLISECONDS.sleep(RETRY_DELAY_MS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        throw new IOException("超过最大重试次数");
    }

    private String parseResponse(String jsonResponse) throws JsonProcessingException {
        try {
            JsonNode rootNode = new ObjectMapper().readTree(jsonResponse);
            JsonNode outputNode = rootNode.path("output").path("choices").get(0).path("message").path("content");
            return outputNode.isTextual() ? outputNode.asText() : "[解析失败]";
        } catch (Exception e) {
            System.out.println("解析响应失败: " + e.getMessage());
            throw e;
        }
    }

    // 异步请求发送方法
    public void sendRequestAsync(String jsonBody, Callback callback) {
        System.out.println("发送异步请求到: " + apiUrl);
        System.out.println("请求内容: " + jsonBody);

        RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .url(apiUrl)
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(body)
                .build();

        client.newCall(request).enqueue(callback);
    }
}
